//
//  YHKHomeViewModel.swift
//  xinlangweiBo2
//
//  Created by 杨和逵 on 16/3/1.
//  Copyright © 2016年 yanghekui. All rights reserved.
//

import UIKit
import AFNetworking


class YHKHomeViewModel: NSObject {
    
    //定义一个数组接收数据
    lazy var array:[YHKHomeCellViewModel] = [YHKHomeCellViewModel]()
    
    
    //MARK:网络加载数据
    func loadData(since_id: Int,max_id: Int,biBao: (count:Int) -> () ){
        
        //设置一个管理者
        let manager = AFHTTPSessionManager()
        
        //拼接参数
        let p = [
            "access_token":YHKLoginModelView.shareInstance.access_token ?? "",
            "max_id":max_id,
            "since_id":since_id]
        
        //发送一个GET请求
        manager.GET("https://api.weibo.com/2/statuses/home_timeline.json", parameters: p, progress: nil, success: { (_, JSON) -> Void in
            
//                        print(JSON)
            
            
            //将JSON数据转为模型
            //1.判断JSON数据是否有值，还将其转为 [String:NSObject]
            if let jsonModel = JSON as? [String:NSObject]{
                
                //2.取出我们需要的数组statuses
                if let statuses = jsonModel["statuses"] as? [[String:NSObject]]{
                    
                    //定义一个临时的数组
                    var temp = [YHKHomeCellViewModel]()
                    
                    //3.遍历数组
                    for statuse in statuses {
                        //4.字典转模型
                        let statuses = YHKStatrsModel(dict:statuse)
                        
                          //将model添加到viewModel里
                        let viewModel = YHKHomeCellViewModel()
                        
                        viewModel.statrsModel = statuses
                        
                        //5.添加到数组里
                        temp.append(viewModel)
                    }
                        ///对数据进行拼接
                        if max_id > 0 {
                            //是不是上啦更多的数据
                            self.array = self.array + temp
                        }else{
                            self.array = temp + self.array
                        }
                        
                        
                        
                        //6.刷新表格,闭包
                          biBao(count: temp.count)
                    }
                    
                }
            
           
            }) { (_, error) -> Void in
                print(error)
        }
        
    }

}
